package org.ptkparty.client.ui;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.ptkparty.client.model.UserProxy;
import org.ptkparty.client.view.players.PlayerCell;

import com.google.gwt.cell.client.Cell;
import com.google.gwt.cell.client.CheckboxCell;
import com.google.gwt.cell.client.CompositeCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.cell.client.HasCell;
import com.google.gwt.editor.client.LeafValueEditor;
import com.google.gwt.user.cellview.client.CellList;
import com.google.gwt.view.client.DefaultSelectionEventManager;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.MultiSelectionModel;

public class UserSelectionCellListView extends CellList<UserProxy> implements LeafValueEditor<List<String>> {

	private ListDataProvider<UserProxy> provider;

	public UserSelectionCellListView(MultiSelectionModel<UserProxy> selectionModel) {
		super(buildCell(selectionModel));
		this.setSelectionModel(selectionModel, DefaultSelectionEventManager.<UserProxy> createCheckboxManager());
	}

	private static Cell<UserProxy> buildCell(final MultiSelectionModel<UserProxy> selectionModel) {
		List<HasCell<UserProxy, ?>> hasCells = new ArrayList<HasCell<UserProxy, ?>>();
		hasCells.add(new HasCell<UserProxy, Boolean>() {

			private CheckboxCell cell = new CheckboxCell(true, false);

			public Cell<Boolean> getCell() {
				return cell;
			}

			public FieldUpdater<UserProxy, Boolean> getFieldUpdater() {
				return new FieldUpdater<UserProxy, Boolean>() {

					@Override
					public void update(int index, UserProxy object, Boolean value) {
						selectionModel.setSelected(object, value);
					}
				};
			}

			public Boolean getValue(UserProxy object) {
				return selectionModel.isSelected(object);
			}
		});
		hasCells.add(new HasCell<UserProxy, UserProxy>() {

			private PlayerCell cell = new PlayerCell();

			public Cell<UserProxy> getCell() {
				return cell;
			}

			public FieldUpdater<UserProxy, UserProxy> getFieldUpdater() {
				return null;
			}

			public UserProxy getValue(UserProxy object) {
				return object;
			}
		});
		return new CompositeCell<UserProxy>(hasCells);
	}

	@Override
	public void setValue(List<String> value) {
		if (value != null) {
			for (UserProxy userProxy : provider.getList()) {
				getSelectionModel().setSelected(userProxy, value.contains(userProxy.getId()));
			}
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<String> getValue() {
		Set<UserProxy> selectedUser = ((MultiSelectionModel<UserProxy>) getSelectionModel()).getSelectedSet();

		List<String> ret = new ArrayList<String>();
		for (UserProxy userProxy : selectedUser) {
			ret.add(userProxy.getId());
		}
		return ret;
	}

	public void setProvider(ListDataProvider<UserProxy> provider) {
		this.provider = provider;
	}

}
